package com.example.demo.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.LoginAttemptMapper;
import com.example.demo.pojo.User.LoginAttempt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginCount extends ServiceImpl<LoginAttemptMapper, LoginAttempt> {
    @Resource
    private LoginAttemptMapper loginAttemptMapper;

    /**
     * 获取当前用户登录失败次数
     *
     * @param userName 用户名
     * @return 登录失败次数
     */
    public Integer getLoginCount(String userName) {
        System.out.println("登录用户为: " + userName);
        LocalDate now = LocalDate.now();
        QueryWrapper<LoginAttempt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_username", userName).eq("login_day", now);
        LoginAttempt attempt = loginAttemptMapper.selectOne(queryWrapper);

        if (attempt == null) {
            return 0;
        }
        Date currentDate = new Date();
        long diff = currentDate.getTime() - attempt.getLoginTime().getTime();
        long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
            if (attempt.getLoginCount() > 5) {
                // 记录登录尝试过多的情况
                log.info("登录失败次数超过5次，当前用户: " + userName + " 需要等待 " + (5 - minutes) + " 分钟后再试。");

            }
        if (minutes >= 5) {
            // 在过了5分钟后删除登录次数
            loginAttemptMapper.deleteById(attempt);
        }
        // 返回当前登录失败次数
        return attempt.getLoginCount();
    }

    /**
     * 获取当前用户登录失败剩余时间
     *
     * @param userName 用户名
     * @return 登录失败剩余时间
     */
    public Integer getLoginTime(String userName) {
        System.out.println("登录用户为: " + userName);
        LocalDate now = LocalDate.now();
        QueryWrapper<LoginAttempt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_username", userName).eq("login_day", now);
        LoginAttempt attempt = loginAttemptMapper.selectOne(queryWrapper);

        if (attempt == null) {
            return 0;
        }
        Date currentDate = new Date();
        long diff = currentDate.getTime() - attempt.getLoginTime().getTime();
        long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
        if (attempt.getLoginCount() > 5) {
            // 记录登录尝试过多的情况
            log.info("登录失败次数超过5次，当前用户: " + userName + " 需要等待 " + (5 - minutes) + " 分钟后再试。");
            return (int) (5 - minutes);
        }
        return null;
    }

    /**
     * 添加登录次数或者新增用户登录记录
     *
     * @param userName 用户名
     */
    public void addCounts(String userName) {
        LoginAttempt loginAttempt = new LoginAttempt();
        QueryWrapper<LoginAttempt> queryWrapper = new QueryWrapper<>();
        LocalDate now = LocalDate.now();
        // 将 LocalDate 转换为 Timestamp，精确到当天的开始时间
        Timestamp nowTimestamp = Timestamp.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
        queryWrapper.eq("login_username", userName).le("login_day", nowTimestamp);
        LoginAttempt existingAttempt = loginAttemptMapper.selectOne(queryWrapper);

        if (existingAttempt == null) {
            Date currentDate = new Date();
            // 如果当天没有登录尝试记录，添加新记录
            loginAttempt.setLoginUsername(userName);
            loginAttempt.setLoginDay(now);
            loginAttempt.setLoginTime(currentDate);
            loginAttempt.setLoginCount(1);
            loginAttemptMapper.insert(loginAttempt);
        } else {
            // 如果已有记录，更新登录次数
            existingAttempt.setLoginCount(existingAttempt.getLoginCount() + 1);
            loginAttemptMapper.updateById(existingAttempt);
        }
    }
}
